package com.lgCore.util;/**
 * Created by by on 2020/11/23 10:10
 */

import com.lgCore.protoModel.ProtoMsg;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;

/**
 * proto byte互转工具
 *
 * @program: sxreader_rpc
 * @author: ligang
 * @create: 2020-11-23 10:10
 */
public class ProtoByteUtil {

    /**
     * proto类转buye数组
     *
     * @param message
     * @return
     */
    public static byte[] protoToByte(ProtoMsg.Message.Builder message) {
        Date date = new Date();
        ProtoMsg.Message message1 = message.build();
        // 将数据写到输出流
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try {
            message1.writeTo(output);
            // 将数据序列化后发送
            byte[] byteArray = output.toByteArray();
//            System.out.println(new Date().getTime()-date.getTime());
            return byteArray;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * proto类转buye数组
     *
     * @param byteArray
     * @return
     */
    public static ProtoMsg.Message byteToProto(byte[] byteArray) {
        // 接收到流并读取
        ByteArrayInputStream input = new ByteArrayInputStream(byteArray);
        // 反序列化
        ProtoMsg.Message message = null;
        try {
            message = ProtoMsg.Message.parseFrom(input);
            return message;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
